using System;
using System.Collections.Generic;

namespace FireStarter.CodeGeneration.Generator
{
    public class ModelStrategyMapper : IModelStrategyMapper
    {
        private readonly IDictionary<Type, IGenerationStrategy> _generationStrategies =
            new Dictionary<Type, IGenerationStrategy>(5);

        public void SetStrategy(Type type, IGenerationStrategy generationStrategy)
        {
            _generationStrategies[type] = generationStrategy;
        }

        public IGenerationStrategy GetStrategy(Type modelElementType)
        {
            Type currentModelElementType = modelElementType;
            do
            {
                if (_generationStrategies.ContainsKey(currentModelElementType))
                    return _generationStrategies[currentModelElementType];
                if (currentModelElementType == typeof (object))
                    throw new ArgumentException("No strategy exists for the given type: " + modelElementType.FullName);
                foreach (Type type in currentModelElementType.GetInterfaces())
                {
                    IGenerationStrategy possibleStrategy = GetStrategy(type);
                    if (possibleStrategy != null) return possibleStrategy;
                }
                currentModelElementType = currentModelElementType.BaseType;
                if (currentModelElementType == null) return null;
            } while (true);
        }
    }
}